package com.student.servlet;

import com.student.pojo.StuInfo;
import com.student.service.StudentService;
import com.student.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * 学生控制层
 */
@WebServlet("/student.do")
public class StudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    StudentService studentService = new StudentServiceImpl();


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        if (opr.equals("login")) {
            //用户登录
            login(request, response);
        } else if (opr.equals("addStudentPage")) {

            //新增用户跳转页面
            addStudentPage(request, response);
        } else if (opr.equals("addStudent")) {

            //添加用户
            addStudent(request, response);
        } else if (opr.equals("register")) {

            //用户注册
            register(request, response);
        } else if (opr.equals("delStudent")) {

            //删除学生
            delStudent(request, response);
        } else if (opr.equals("seeByIdStudent")) {

            //通过编号查询学生信息
            seeByIdStudent(request, response);
        } else if (opr.equals("updateStudent")) {

            //修改学生信息
            updateStudent(request, response);
        } else if (opr.equals("updatePasswordPage")) {

            //修改当前用户的密码跳转页面
            updatePasswordPage(request, response);
        } else if (opr.equals("updatePassword")) {

            //修改当前用户的密码
            updatePassword(request, response);
        } else if (opr.equals("seeStudentPage")) {

            //查询个人学生信息
            seeStudentPage(request, response);
        } else if (opr.equals("seeStudent")) {

            //查询学生
            seeStudent(request, response);
        }
    }

    /**
     * 修改当前用户密码
     *
     * @param request
     * @param response
     */
    private void updatePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Integer id = Integer.parseInt(request.getParameter("id"));
        StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
        //从页面拿值
        String password = request.getParameter("password");
        StuInfo stuInfoPojo = new StuInfo();
        stuInfoPojo.setId(id);
        stuInfoPojo.setName(stuInfo.getName());
        stuInfoPojo.setPassword(password);
        stuInfoPojo.setAge(stuInfo.getAge());
        stuInfoPojo.setWeight(stuInfo.getWeight());
        stuInfoPojo.setHeight(stuInfo.getHeight());
        stuInfoPojo.setSex(stuInfo.getSex());
        stuInfoPojo.setRole(stuInfo.getRole());
        try {
            int i = studentService.updateStudent(stuInfoPojo);
            if (i > 0) {
                out.print("<script>alert('密码修改成功！');" +
                        "window.location.href='/student.do?opr=updatePasswordPage'</script>");
            } else {
                out.print("<script>alert('密码修改失败！');</script>");
            }
        } catch (NullPointerException nullE) {
            out.print("<script>alert('密码修改失败！报错');</script>");
        }
    }

    /**
     * 跳转到修改用户页面
     *
     * @param request
     * @param response
     */
    private void updatePasswordPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
        request.setAttribute("stuInfo", stuInfo);

        System.out.println(stuInfo);
        System.out.println("跳转页面方法！！！");

        //1.设置首页动态包含的页面值
        request.setAttribute("changePage", "updatePassword.jsp");
        request.getRequestDispatcher("/homepage.jsp").forward(request, response);
    }

    /**
     * 跳转到新增用户页面
     *
     * @param request
     * @param response
     */
    private void addStudentPage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
        request.setAttribute("stuInfo", stuInfo);
        //1.设置首页动态包含的页面值
        request.setAttribute("changePage", "addStudent.jsp");
        request.getRequestDispatcher("/homepage.jsp").forward(request, response);
    }

    /**
     * 查询个人学生信息方法
     *
     * @param request
     * @param response
     */
    private void seeStudentPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
        request.setAttribute("stuInfo", stuInfo);
        //1.设置首页动态包含的页面值
        request.setAttribute("changePage", "studentInfo.jsp");
        request.getRequestDispatcher("/homepage.jsp").forward(request, response);
    }

    /**
     * 查询方法
     *
     * @param request
     * @param response
     */
    private void seeStudent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        List<StuInfo> stuInfoList = null;
        String name = request.getParameter("name");
        //姓名
        if (name != "" && name != null) {
            stuInfoList = studentService.seeStudent(null, name);
        } else {
            stuInfoList = studentService.seeStudent(null, null);
        }
        request.setAttribute("stuInfoList", stuInfoList);
        StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
        request.setAttribute("stuInfo", stuInfo);
        //1.设置首页动态包含的页面值
        request.setAttribute("changePage", "seestudents.jsp");
        request.getRequestDispatcher("/homepage.jsp").forward(request, response);
    }

    /**
     * 通过学生编号查询学生信息
     *
     * @param request
     * @param response
     */
    private void seeByIdStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Integer id = Integer.parseInt(request.getParameter("id"));
        try {
            //1.设置首页动态包含的页面值
            request.setAttribute("changePage", "updateStudent.jsp");
            List<StuInfo> stuInfoList = studentService.seeStudent(id, null);
            request.setAttribute("stuInfoList", stuInfoList);
            StuInfo stuInfo = (StuInfo) request.getSession().getAttribute("valueAfterLogin");//取session
            request.setAttribute("stuInfo", stuInfo);
            request.getRequestDispatcher("/homepage.jsp").forward(request, response);
        } catch (NullPointerException | ServletException nullE) {
            nullE.printStackTrace();
            out.print("<script>alert('查询带id的用户失败！');</script>");
        }
    }

    /**
     * 修改方法
     *
     * @param request
     * @param response
     */
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Integer id = Integer.parseInt(request.getParameter("id"));
        //从页面拿值
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Integer age = Integer.parseInt(request.getParameter("age"));
        double weight = Double.parseDouble(request.getParameter("weight"));
        double height = Double.parseDouble(request.getParameter("height"));
        String sex = request.getParameter("sex");
        String role = request.getParameter("role");
        String classId = request.getParameter("classId");

        StuInfo stuInfo = new StuInfo();
        stuInfo.setId(id);
        stuInfo.setName(name);
        stuInfo.setPassword(password);
        stuInfo.setAge(age);
        stuInfo.setWeight(weight);
        stuInfo.setHeight(height);
        stuInfo.setSex(sex);
        stuInfo.setRole(role);

        try {
            int i = studentService.updateStudent(stuInfo);
            if (i > 0) {
                out.print("<script>alert('修改成功！');" +
                        "window.location.href='student.do?opr=seeStudent'</script>");
            } else {
                out.print("<script>alert('修改失败！');</script>");
            }
        } catch (NullPointerException nullE) {
            out.print("<script>alert('学生信息修改失败！');</script>");
        }
    }

    /**
     * 删除方法
     *
     * @param request
     * @param response
     */
    private void delStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Integer id = Integer.parseInt(request.getParameter("id"));
        try {
            int i = studentService.delStudent(id);
            if (i > 0) {
                out.print("<script>alert('删除成功！');" +
                        "window.location.href='student.do?opr=seeStudent'</script>");
            } else {
                out.print("<script>alert('删除失败！');</script>");
            }
        } catch (NullPointerException nullE) {
            out.print("<script>alert('删除失败！');</script>");
        }
    }

    /**
     * 添加方法
     *
     * @param request
     * @param response
     */
    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Integer age = Integer.parseInt(request.getParameter("age"));
        double weight = Double.parseDouble(request.getParameter("weight"));
        double height = Double.parseDouble(request.getParameter("height"));
        String sex = request.getParameter("sex");
        String role = request.getParameter("role");
        String classId = request.getParameter("classId");

        StuInfo stuInfo = new StuInfo();
        stuInfo.setName(name);
        stuInfo.setPassword(password);
        stuInfo.setAge(age);
        stuInfo.setWeight(weight);
        stuInfo.setHeight(height);
        stuInfo.setSex(sex);
        stuInfo.setRole(role);
        int count = studentService.addStudent(stuInfo);
        if (count > 0) {
            out.print("<script>alert('新增成功！');" +
                    "window.location.href='student.do?opr=seeStudent'</script>");
        } else {
            out.print("<script>alert('新增失败！');</script>");
        }
    }

    /**
     * 用户注册
     *
     * @param request
     * @param response
     */
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        Integer age = Integer.parseInt(request.getParameter("age"));
        double weight = Double.parseDouble(request.getParameter("weight"));
        double height = Double.parseDouble(request.getParameter("height"));
        String sex = request.getParameter("sex");
        String classId = request.getParameter("classId");

        StuInfo stuInfo = new StuInfo();
        stuInfo.setName(name);
        stuInfo.setPassword(password);
        stuInfo.setAge(age);
        stuInfo.setWeight(weight);
        stuInfo.setHeight(height);
        stuInfo.setSex(sex);
        stuInfo.setRole("用户");

        int count = studentService.addStudent(stuInfo);
        if (count > 0) {
            out.print("<script>alert('注册成功！');" +
                    "window.location.href='register.jsp'</script>");
        } else {
            out.print("<script>alert('注册失败！');</script>");
        }
    }

    /**
     * 登录方法
     *
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");//获取姓名
        String password = request.getParameter("password");//获取密码
        String role = request.getParameter("role");//获取角色

        // 记录日志
        try {
            StuInfo stuInfo = studentService.studentLogin(name, password, role);
            if (stuInfo == null) {
                out.print("<script>alert('登录失败！');window.location='login.jsp';</script>");
            } else {
                request.getSession().setAttribute("valueAfterLogin", stuInfo);//存session
                request.setAttribute("stuInfo", stuInfo);
                request.getRequestDispatcher("/homepage.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('登录失败！');window.location='login.jsp';</script>");
        }
    }


}
